import $ from 'jquery'

document.addEventListener('DOMContentLoaded', () => {
    const CACHE_KEYS = {
        ABT_CODE_LIST: 'ABT_CODE_LIST'
    }

    function execFunc(func, ...params) {
        typeof func === 'function' && func(...params)
    }

    function getFindAbtButton() {
        return $('#findAbtButton')
    }

    function getSearchRatioButton() {
        return $('#searchButton')
    }

    function getResultTextArea() {
        return $('#result')
    }

    function sendMessage(data) {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            var activeTab = tabs[0]
            chrome.tabs.sendMessage(activeTab.id, data)
        })
    }

    function saveAbtCodeListToStorage(abtCodeList) {
        localStorage.setItem(CACHE_KEYS.ABT_CODE_LIST, JSON.stringify(abtCodeList))
    }

    function getAbtCodeListFromStorage() {
        let abtCodeList = {}

        let codeListString = localStorage.getItem(CACHE_KEYS.ABT_CODE_LIST)
        if (codeListString) {
            try {
                abtCodeList = JSON.parse(codeListString)
            } catch (error) {
            }
        }

        return abtCodeList
    }

    chrome.runtime.onMessage.addListener(
        function (data) {
            let { action, payload } = data
            switch (action) {
                case 'abt_result':
                    if (payload && payload.length) {
                        const abtListWrapper = payload.reduce((prev, next) => { prev[next] = {}; return prev; }, {})
                        setResult(abtListWrapper, true)

                        setMessage(`共查找到${payload.length}个ab实验号`)
                    } else {
                        setMessage('未找到任何abt_code')
                    }
                    break
                default:
                    break
            }
        })

    function findAbtCodesOnPageAsync() {
        sendMessage({ action: 'find_abt' })
    }

    function genAbtListJsonString(abtListWrapper) {
        return JSON.stringify(abtListWrapper, null, 2)
    }

    function setResult(json, save) {
        const jsonString = genAbtListJsonString(json)

        getResultTextArea().html(jsonString)
        save && saveAbtCodeListToStorage(json)
    }

    function setMessage(msg) {
        $('#msg').html(msg)
    }

    function getAbtResultObject() {
        const msgString = getResultTextArea().html()
        let msgObject = null

        try {
            msgObject = JSON.parse(msgString)
        } catch (error) {
        }

        return msgObject
    }

    getFindAbtButton().bind('click', ev => {
        setResult({}, false)
        setMessage('滚屏查找中...')
        findAbtCodesOnPageAsync()
    })

    function getAbtIdList(abtCodeList, onFetchAbtIds) {
        // Online国际的搜索Url
        const defaultUrl = `http://abtestmgr.ctripcorp.com/mgm/Experiment/GetInfos?expcode=&exptype=&expstatus=&expchannel=1&page=1&rp=500&sortname=beginTime&sortorder=DESC`

        // 搜不到就用code关键字搜
        const getSearchUrl = code => `http://abtestmgr.ctripcorp.com/mgm/Experiment/GetInfos?expcode=${code}&exptype=&expstatus=&expchannel=&page=1&rp=20&sortname=beginTime&sortorder=DESC`

        let map = {}
        let keywordSearchCount = 0

        const seachByUrl = (url, callback) => {
            $.get(url, function (data) {
                const useKeyWordSearch = url !== defaultUrl
                if (useKeyWordSearch) {
                    keywordSearchCount++
                }

                const rows = data.rows

                if (rows && rows.length) {
                    let html = document.createElement('html')
                    rows.forEach(row => {
                        const currentRowCode = row.Code
                        html.innerHTML = currentRowCode
                        const anchor = html.querySelector('a')
                        if (anchor) {
                            const abtCode = anchor.textContent
                            if (abtCode && row.ID && abtCodeList.includes(abtCode)) {
                                map[abtCode] = { id: row.ID }
                                if (useKeyWordSearch) {
                                    keywordSearchCount--
                                }
                            }
                        }
                    })
                }

                if ((Object.keys(map).length + keywordSearchCount) === abtCodeList.length) {
                    execFunc(onFetchAbtIds, map, onGetAllAbtRatioList)
                } else {
                    execFunc(callback)
                }
            }).catch(err => {
                setMessage('查询出现异常：' + JSON.stringify(err))
            })
        }

        seachByUrl(defaultUrl, () => {
            // 是否所有code使用默认url都搜索到了，如果没有，就用code作为关键字重新搜索
            const allFoundAbtCodes = Object.keys(map)
            const notFoundAbtCodes = abtCodeList.filter(code => !allFoundAbtCodes.includes(code))
            notFoundAbtCodes.forEach(code => {
                seachByUrl(getSearchUrl(code), null)
            })
        })

    }

    function getSingleAbtRatio(id, onGetAbtVersionWrapper) {
        const url = `http://abtestmgr.ctripcorp.com/mgm/ExpWizardView/Step3?ExpID=${id}&OperType=EDIT`
        $.get(url, function (doc) {
            let rootHtml = document.createElement('html')
            rootHtml.innerHTML = doc

            const versionList = Array.from(rootHtml.querySelectorAll('#result3 tr:first-child td')).map(td => td.textContent.trim().replace('版本 ', '')).filter((val, index) => index > 0)
            const ratioList = Array.from(rootHtml.querySelectorAll('#result3 tr:last-child td')).map(td => td.textContent.trim().replace(' ', ''))
            const ratioWrapper = versionList.reduce((prev, next) => {
                const ratio = ratioList[versionList.indexOf(next)]
                if (ratio !== '0%') {
                    prev[next] = ratio
                }

                return prev
            }, {})

            execFunc(onGetAbtVersionWrapper, ratioWrapper)
        }).catch(err => {
            setMessage('查询出现异常：' + JSON.stringify(err))
            execFunc(onGetAbtVersionWrapper, {})
        })
    }

    function getAbtRatioList(map, onFinishAll) {
        const abtCodeList = Object.keys(map)
        if (abtCodeList.length) {
            let mapWithRatio = {}

            for (let i = 0; i < abtCodeList.length; i++) {
                const abtCode = abtCodeList[i]
                const abtWrapper = map[abtCode]
                const id = abtWrapper.id

                getSingleAbtRatio(id, wrapper => {
                    mapWithRatio[abtCode] = { ...wrapper }
                    if (Object.keys(mapWithRatio).length === abtCodeList.length) {
                        execFunc(onFinishAll, mapWithRatio)
                    }
                })
            }

        }
    }

    function onGetAllAbtRatioList(mapWithRatio) {
        setMessage('查询完毕，ABT流量如下，已在页面标记：')
        setResult(mapWithRatio, true)
        sendMessage({ action: 'display_abt_ratio', payload: mapWithRatio })
    }

    getSearchRatioButton().bind('click', () => {
        const abtResult = getAbtResultObject()

        if (abtResult) {
            const abtCodes = Object.keys(abtResult)
            if (abtCodes.length) {
                setMessage('开始查询ABT各版本流量，请稍候...')
                getAbtIdList(abtCodes, getAbtRatioList)
            } else {
                setMessage('请先查找页面abt或手动输入abt，再进行查询')
            }
        } else {
            setMessage('abt格式有误，请确认后再试')
        }
    })

    // 恢复 codes
    const abtCodeList = getAbtCodeListFromStorage()
    if (abtCodeList) {
        setResult(abtCodeList, false)
    }
})